package com.ksm.zyz.common.servlet;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码实现
 */
public class ValidateCodeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public static final String VALIDATE_CODE = "validateCode";
	
	private int w = 80;
	private int h = 30;
	
	public ValidateCodeServlet(){
		super();
	}
	
	public void destory(){
		super.destroy();
	}
	
	public static boolean validate(HttpServletRequest request,String validateCode){
		String code = (String)request.getSession().getAttribute(VALIDATE_CODE);
		return validateCode.toUpperCase().equals(code);
	}
	
	private void createImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		response.setHeader("Pragma", "no-cache"); //没有缓存
		response.setHeader("Cache-Control", "no-cache"); //没有缓存
		response.setDateHeader("Expires", 0); //设置过期的时间期限  
		response.setContentType("image/jpeg"); //设置生成文件类型
		
		/*
		 * 得到参数宽和高都为数字时，则使用设置宽和高，否则使用默认值 
		 */
		String width = request.getParameter("width");
		String height = request.getParameter("height");
		if(StringUtils.isNumeric(width)&&StringUtils.isNumeric(height)){
			w = NumberUtils.toInt(width);
			h = NumberUtils.toInt(height);
		}
		BufferedImage image = new BufferedImage(w,h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		
		/*
		 * 生成背景
		 */
		createBackground(g);
		//生成字符
		String s = createCharacter(g);
		request.getSession().setAttribute(VALIDATE_CODE, s);
		g.dispose();
		OutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		out.close();
	}
	
	/**
	 * 设置颜色
	 * @param fc
	 * @param bc
	 * @return
	 */
	private Color getRandColor(int fc, int bc){
		Random random = new Random();
		if(fc>255){
			fc = 255;
		}
		if(bc>255){
			bc = 255;
		}
		return new Color(fc+random.nextInt(bc-fc),fc+random.nextInt(bc-fc),fc+random.nextInt(bc-fc));
	}
	
	private void createBackground(Graphics g){
		//填充背景
		g.setColor(getRandColor(220,250));
		g.fillRect(0, 0, w, h);
		//加干扰线
		for(int i=0;i<8;i++){
			g.setColor(getRandColor(40,150));
			Random random = new Random();
			int x1 = random.nextInt(w);
			int y1 = random.nextInt(h);
			int x2 = random.nextInt(w);
			int y2 = random.nextInt(h);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	
	/**
	 * 生成字符
	 * @param g
	 * @return
	 */
	private String createCharacter(Graphics g){
		char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
				'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
		String[] fontTypes = {"\u5b8b\u4f53","\u65b0\u5b8b\u4f53","\u9ed1\u4f53","\u6977\u4f53","\u96b6\u4e66"};
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		for(int i=0;i<4;i++){
			String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
			g.setColor(new Color(50+random.nextInt(100),50+random.nextInt(100),50+random.nextInt(100)));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD,26));
			g.drawString(r, 15*i+5, 19+random.nextInt(8));
			s.append(r);
		}
		return s.toString();
	}
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String validateCode = request.getParameter(VALIDATE_CODE);
		if(StringUtils.isNoneBlank(validateCode)){
			response.setContentType("text/html;charset=UTF-8");
			response.getOutputStream().print(validate(request,validateCode)?"true":"false");
		}else{
			this.doPost(request, response);
		}
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
		createImage(request, response);
	}
	
}
